<?php

namespace App\Services\Stats\Platform;

use App\Core\Traits\Numeral;
use App\Models\Game\Platform\Org;
use App\Models\Game\Settlement\Info;
use App\Services\Service;
use App\Services\Traits\DatabaseMysql;
use App\Models\Admin\Stats\Settlement\All as StatsAll;
use App\Models\Admin\Stats\Settlement\Game as StatsGame;
use App\Models\Admin\Stats\Settlement\GameScene as StatsGameScene;
use Helper\Timed;

class SettlementService extends Service
{
    use DatabaseMysql, Numeral;

	/**
	 * 获取数据列表【全部】
	 *
	 * @param \Illuminate\Http\Request $request
	 * @param bool $export
	 * @return \Illuminate\Database\Eloquent\Collection[]|int[]|array[]
	 */
	public function all($request, $export = false)
	{
		return $this->getList($request, "currency, plat_code, line_code, timed", $export);
	}

	/**
	 * 获取数据列表【游戏】
	 *
	 * @param \Illuminate\Http\Request $request
	 * @param bool $export
	 * @return \Illuminate\Database\Eloquent\Collection[]|int[]|array[]
	 */
	public function game($request, $export = false)
	{
		return $this->getList($request, "game_id, currency, plat_code, line_code, timed", $export);
	}

	/**
	 * 获取数据列表【游戏场景】
	 *
	 * @param \Illuminate\Http\Request $request
	 * @param bool $export
	 * @return \Illuminate\Database\Eloquent\Collection[]|int[]|array[]
	 */
	public function gameScene($request, $export = false)
	{
		return $this->getList($request, StatsGameScene::query(), $export);
	}

	/**
	 * 获取数据列表
	 *
	 * @param \Illuminate\Http\Request $request
	 * @param \Illuminate\Database\Eloquent\Builder $query
	 * @param bool $export
	 * @return \Illuminate\Database\Eloquent\Collection[]|int[]|array[]
	 */
	public function getList($request, $groupBy, $export)
	{
		$query = Info::query();

		$query->where('status', Info::STATUS_NORMAL)->where('player_type', Info::PLAYER_TYPE);

		// 筛选【时间】
		$this->makeWhereParamDatetimeTimeZone($request, $query, 'end_time');
		// 筛选【平台】
		$this->makeWhereParamOrg($request, $query);
		// 筛选【平台】【排除】
		$this->makeWhereParamNot($request, 'plat_code_exclude', $query, 'plat_code');
		// 筛选【游戏】
		$this->makeWhereParam($request, 'game_id', $query);
		// 筛选【游戏】【排除】
		$this->makeWhereParamNot($request, 'game_id_exclude', $query, 'game_id');
		// 筛选【币种】
		$this->makeWhereParam($request, 'currency', $query);
		// 筛选【币种】【排除】
		$this->makeWhereParamNot($request, 'currency_exclude', $query, 'currency');
		// 筛选【场景】
		$this->makeWhereParam($request, 'scene_id', $query);

		// 统计数据
		$stats = $this->getStats(clone $query);

		// 排序
		$this->makeOrderParam($request, $query);

		//分页
		$this->makePaginationParam($request, $query);
		// 获取数据
		list($collection, $total) = $this->getData($request, $query, $groupBy);

		return [
			$collection,
			$total,
			$stats
		];
	}

	/**
	 * 获取数据和总条数
	 *
	 * @param \Illuminate\Database\Eloquent\Builder $query
	 * @return array
	 */
	private function getData($request, $query, $groupBy)
	{
		//转换指定时区
		date_default_timezone_set(Timed::getTimezoneName());
		$timezone = Timed::getTimeCode();
		$columns[] ="DATE(CONVERT_TZ(DATE_FORMAT(FROM_UNIXTIME(end_time), '%Y-%m-%d %H:%i:%s'), '+08:00', '".(preg_replace("/^UTC/", "", $timezone))."')) as timed";
		$columns[] = 'currency';
		$columns[] = 'game_id';
		$columns[] = 'plat_code';
		$columns[] = 'line_code';
		$columns[] = 'COUNT(*) as doc_count';
		$columns[] = 'COUNT(DISTINCT uid) as player_count';
		$columns[] = 'SUM(bet_num) as bet_num';
		$columns[] = '-IFNULL(SUM(gain_player),0) as amount';
		$columns[] = 'IFNULL(SUM(gain_player),0) as gain_player';
		$columns[] = 'IFNULL(SUM(bet_base),0) as bet_base';
		$columns[] = 'IFNULL(SUM(bet_num),0) as bet_num';
		$columns[] = "-IFNULL(CAST(SUM(usd->'$.gain_player') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS usd_amount";
		$columns[] = "IFNULL(CAST(SUM(usd->'$.gain_player') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS usd_gain_player";
		$columns[] = "IFNULL(CAST(SUM(usd->'$.bet_base') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS usd_bet_base";
		$columns[] = "IFNULL(CAST(SUM(usd->'$.bet_num') AS DECIMAL({$this->decimals()},{$this->precision()})),0) AS usd_bet_num";

		$query->groupByRaw($groupBy);

		return Info::dbConnection()->transaction(function () use ($request, $query, $columns) {
			// 查询数据
			$collection = $query->getQuery()
				->selectRaw('SQL_CALC_FOUND_ROWS ' . implode(',', $columns))
				->orderBy('currency')
				->get();

			// 数据条数
			$total = (int)Info::dbConnection()->select("SELECT FOUND_ROWS() as `row_count`")[0]['row_count'];

			$collectionArr = $collection->toArray();
			//查询org
			$plat_codes = array_column($collectionArr, 'plat_code');
			$orgs = Org::whereIn('code', $plat_codes)->select(['code', 'name'])->get()->toArray();
			$orgArr = array_column($orgs, 'name', 'code');

			$collection->transform(function ($item)use($request, $orgArr) {

				$item['timed'] = strtotime($item['timed']);

				return $item + ['usd'=>
					                [
						                'amount' => $item['usd_amount'],
						                'bet_base' => $item['usd_bet_base'],
						                'bet_num' => $item['usd_bet_num'],
						                'gain_player' => $item['usd_gain_player'],
					                ]
					] + [
						'time_zone' => Timed::getTimezoneName(),
					] + ['org' => [
						'code' => $item['plat_code'],
						'name' => isset($orgArr[$item['plat_code']]) ? $orgArr[$item['plat_code']] : $item['plat_code'],
					],
					];
			});

			return [$collection, $total];
		});
	}


	/**
	 * 获取统计信息
	 *
	 * @param \Illuminate\Database\Eloquent\Builder $query
	 * @return array
	 */
	private function getStats($query)
	{
		// USD
		$usd = (clone $query)->getQuery()->selectRaw(implode(',', [
			'COUNT(*) as doc_count',
			'COUNT(DISTINCT uid) as player_count',
			"-CAST(SUM(usd->'$.gain_player') AS DECIMAL({$this->decimals()},{$this->precision()})) AS amount",
			"CAST(SUM(usd->'$.gain_player') AS DECIMAL({$this->decimals()},{$this->precision()})) AS gain_player",
			"CAST(SUM(usd->'$.bet_base') AS DECIMAL({$this->decimals()},{$this->precision()})) AS bet_base",
			"CAST(SUM(usd->'$.bet_num') AS DECIMAL({$this->decimals()},{$this->precision()})) AS bet_num",
		]))->first();

		// 分币种
		$sts = (clone $query)->getQuery()->selectRaw(implode(',', [
			'COUNT(DISTINCT uid) as player_count',
			'COUNT(*) as doc_count',
			'-IFNULL(SUM(gain_player),0) as amount',
			'IFNULL(SUM(gain_player),0) as gain_player',
			'IFNULL(SUM(bet_base),0) as bet_base',
			'IFNULL(SUM(bet_num),0) as bet_num',
			'currency',
		]))
			->groupBy('currency')
			->get();

		return [
			'usd' => $usd,
			'sts' => $sts,
		];
	}

	/**
	 * 获取平台统计USD
	 *
	 * @param \Illuminate\Http\Request $request
	 * @param bool $export
	 * @return \Illuminate\Database\Eloquent\Collection[]|array[]
	 */
	public function getUsd($request, $export = false)
	{
		$query = Info::query();

		$query->where('status', Info::STATUS_NORMAL)->where('player_type', Info::PLAYER_TYPE);
		// 筛选【时间】
		$this->makeWhereParamDatetimeTimeZone($request, $query, 'end_time');
		// 筛选【平台】
		$this->makeWhereParamOrg($request, $query);
		// 筛选【平台】【排除】
		$this->makeWhereParamNot($request, 'plat_code_exclude', $query, 'plat_code');
		// 筛选【游戏】
		$this->makeWhereParam($request, 'game_id', $query);
		// 筛选【游戏】【排除】
		$this->makeWhereParamNot($request, 'game_id_exclude', $query, 'game_id');

		$columns[] = 'plat_code';
		$columns[] = 'line_code';
		$columns[] = 'COUNT(*) as doc_count';
		$columns[] = 'COUNT(DISTINCT uid) as player_count';
		$columns[] = "CAST(SUM(usd->'$.bet_base') AS DECIMAL({$this->decimals()},{$this->precision()})) AS bet_base";
		$columns[] = "CAST(SUM(usd->'$.bet_num') AS DECIMAL({$this->decimals()},{$this->precision()})) AS bet_num";
		$columns[] = "CAST(SUM(usd->'$.gain_player') AS DECIMAL({$this->decimals()},{$this->precision()})) AS gain_player";
		$columns[] = "-CAST(SUM(usd->'$.gain_player') AS DECIMAL({$this->decimals()},{$this->precision()})) AS amount";

		// 查询数据
		$collection = (clone $query)->getQuery()->selectRaw(implode(',', $columns))
			->groupBy('plat_code', 'line_code')
			->orderBy(
				$request->input('order_column', 'doc_count'),
				$request->input('order', 'desc')
			)
			->get();

		$collectionArr = $collection->toArray();
		//查询org
		$plat_codes = array_column($collectionArr, 'plat_code');
		$orgs = Org::whereIn('code', $plat_codes)->select(['code', 'name'])->get()->toArray();
		$orgArr = array_column($orgs, 'name', 'code');

		$collection->transform(function ($item)use($orgArr) {
			return $item + ['org' => [
					'code' => $item['plat_code'],
					'name' => isset($orgArr[$item['plat_code']]) ? $orgArr[$item['plat_code']] : $item['plat_code'],
				],];
		});

		// 合计USD
		$stats = $query->getQuery()->selectRaw(implode(',', [
			'COUNT(*) as doc_count',
			'COUNT(DISTINCT uid) as player_count',
			"-CAST(SUM(usd->'$.gain_player') AS DECIMAL({$this->decimals()},{$this->precision()})) AS amount",
			"CAST(SUM(usd->'$.gain_player') AS DECIMAL({$this->decimals()},{$this->precision()})) AS gain_player",
			"CAST(SUM(usd->'$.bet_base') AS DECIMAL({$this->decimals()},{$this->precision()})) AS bet_base",
			"CAST(SUM(usd->'$.bet_num') AS DECIMAL({$this->decimals()},{$this->precision()})) AS bet_num",
		]))->first();

		return [
			$collection,
			$stats
		];
	}
}
